<template>
  <div>
    <!-- 搜索页面头部 -->
    <div class="search-header">
      <!-- 后退按钮 -->
      <van-icon name="arrow-left" color="white" size="0.48rem" class="goback" @click="$router.back()"/>
      <!-- 搜索组件 -->
      <van-search
      v-fofo
      v-model.trim="kw"
      @input="inputFn"
      @search="searchFn"
      placeholder="请输入搜索关键词" background="#007BFF" shape="round" />

    </div>
      <!-- 搜索建议列表 -->
    <div class="sugg-list" v-if="kw.length !== 0">
        <div class="sugg-item" v-for="(item,index) in suggestList" :key ="index"
        v-html="ligthFn(item,kw)"
        @click="suggestClickFn(item)"
        >
        </div>
    </div>

  <!-- 搜索历史 -->
    <div class="search-history" v-else>
        <!-- 标题 -->
        <van-cell title="搜索历史">
            <!-- 使用 right-icon 插槽来自定义右侧图标 -->
            <template #right-icon >
                <van-icon name="delete" class="search-icon" @click="clearFn" />
            </template>
        </van-cell>

        <!-- 历史列表 -->
        <div class="history-list">
            <span class="history-item" v-for="(item,index) in history" :key="index"
            @click="historyClickFn(item)"
            >{{item}}</span>
        </div>
    </div>

  </div>
</template>

<script>
import { suggestListAPI } from '@/api'
import { getStorage, setStorage } from '@/utils/storage.js'
export default {
  data () {
    return {
      kw: '', // 搜索关键字
      timer: null,
      suggestList: [],
      // 给history的时候在转会数组
      history: JSON.parse(getStorage('his')) || []
    }
  },
  methods: {
    // 防抖
    inputFn () {
      clearInterval(this.timer)
      if (this.kw.length === 0) {
        this.suggestList = []
      } else {
        this.timer = setTimeout(async () => {
          if (this.kw.length === 0) return
          console.log(this.kw)
          const res = await suggestListAPI({
            keywords: this.kw
          })
          console.log(res)
          this.suggestList = res.data.data.options
        }, 300)
      }
    },
    // 关键字高亮
    ligthFn (originStr, target) {
      // 如果你要使用变量,作为正则的匹配条件,不能用语法糖简化写法
      const reg = new RegExp(target, 'ig') // i忽略大小写,全局匹配
      return originStr.replace(reg, (match) => {
        // match就是匹配中时,原字符字符串里的那个字符,用人家原来的,只是我们换个颜色
        return `<span style="color:red;" >${match}</span>`
      })
    //   return originStr.replaceAll(target, `<span style="color:red;" >${target}</span>`)
    },
    moveFn (thekw) {
      setTimeout(() => {
        this.$router.push({
          path: `/SearchResult/${thekw}`
        })
      }, 0)
    },
    // 输入框-搜索事件
    searchFn () {
      if (this.kw.length > 0) {
        this.history.push(this.kw)
        this.moveFn(this.kw)
      }
    },
    // 联想菜单点击事件
    suggestClickFn (str) {
      this.history.push(str)
      this.moveFn(str)
    },
    // 搜索历史事件
    historyClickFn (str) {
      this.moveFn(str)
    },
    // 清空历史事件
    clearFn () {
      this.history = []
    }
  },
  watch: {
    history: {
      deep: true,
      handler () {
        // es6 新增的两种引用类型(set,map)
        // 删掉数组中重复的元素
        const theSet = new Set(this.history)
        console.log(theSet)
        const arr = Array.from(theSet)
        // 保存本地必须以字符串格式
        setStorage('his', JSON.stringify(arr))
      }
    }
  }
}
</script>

<style scoped lang="less">
.search-header {
  height: 46px;
  display: flex;
  align-items: center;
  background-color: #007bff;
  overflow: hidden;
  /*后退按钮*/
  .goback {
    padding-left: 14px;
  }
  /*搜索组件*/
  .van-search {
    flex: 1;
  }
}
/*搜索建议列表样式 */
.sugg-list {
  .sugg-item {
    padding: 0 15px;
    border-bottom: 1px solid #f8f8f8;
    font-size: 14px;
    line-height: 50px;
    // 实现省略号的三行代码
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
/**搜索历史 */
.search-icon {
  font-size: 16px;
  line-height: inherit;
}

.history-list {
  padding: 0 10px;
  .history-item {
    display: inline-block;
    font-size: 12px;
    padding: 8px 14px;
    background-color: #efefef;
    margin: 10px 8px 0px 8px;
    border-radius: 10px;
  }
}
</style>
